import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Table, Form, Input, Button, Modal, List } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import {
  DataType,
  GetOrder,
  getOrderAPI,
  refundAPI,
  test1API,
} from '@/service/order';
import useWebSocket from '@/utils/WebSocket';
import { Model } from 'echarts';
import { Complaint, ComplaintAPI, GetComplaintAPI } from '@/service/complaints';

const queryPage: GetOrder = {
  current: 1,
  size: 10,
  masterId: 0,
  restaurantId: 0,
  sortField: '',
  sortOrder: '',
};

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: string;
  sortOrder?: string;
  filters?: Record<string, FilterValue>;
}

const { Search } = Input;

const App: React.FC = () => {
  const [data, setData] = useState<DataType[]>();
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  const masterId = localStorage.masterId;
  queryPage.masterId = masterId;
  const restaurantId = localStorage.restaurant;
  queryPage.restaurantId = restaurantId;
  const times = {
    1: '上午',
    2: '中午',
    3: '下午',
    4: '晚上',
  };
  const [webSocket, sendMessage, lastMessage, isConnected] = useWebSocket({
    url: 'ws://localhost:10001/websocket/admin', //这里放长链接
    onOpen: () => {
      //连接成功
      console.log('WebSocket connected');
    },
    onClose: () => {
      //连接关闭
      console.log('WebSocket disconnected');
    },
    onError: (event) => {
      //连接异常
      console.error('WebSocket error:', event);
    },
    onMessage: (message) => {
      Modal.info({
        title: '新订单',
        content: message,
        onOk() {
          window.location.href = '/merchantOrder';
        },
      });
    },
  });
  const refund = async (id: number) => {
    Modal.confirm({
      title: '审批',
      content: '是否同意退款',
      okText: '同意',
      cancelText: '拒绝',
      async onOk() {
        try {
          await test1API(id);
          fetchData();
        } catch (error) {
          Modal.error({
            title: '审批失败',
            content: error,
          });
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const columns: ColumnsType<DataType> = useMemo(
    () => [
      {
        title: '座位名称',
        dataIndex: 'seatName',
        render: (seatName) => `${seatName}`,
        width: '10%',
      },
      {
        title: '金额',
        dataIndex: 'orderMoney',
        sorter: true,
        render: (orderMoney) => `${orderMoney} 分`,
        width: '10%',
      },
      {
        title: '预定时间',
        dataIndex: 'datePeriod',
        sorter: true,
        render: (datePeriod, data) => {
          const date = datePeriod.split(' ')[0];
          return `${date} ${times[data.timePeriod]}`;
        },
        width: '15%',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: true,
        render: (createTime) => `${createTime}`,
        width: '15%',
      },
      {
        title: '订单详情',
        dataIndex: 'dishNameList',
        render: (dishNameList) => {
          return dishNameList.map((item: any) => {
            return `${item.dishName} ${item.dishNum}份` + ' ';
          });
        },
        width: '20%',
      },
      {
        title: '是否支付',
        dataIndex: 'status',
        sorter: true,
        render: (status, data) => {
          //如果是未支付返回按钮，已支付返回已支付
          if (status === 0 && new Date(data.datePeriod) > new Date()) {
            return '未支付';
          } else if (status === 0 && new Date(data.datePeriod) <= new Date()) {
            return '已取消';
          } else if (status === 1) {
            return '已支付';
          } else if (status === 2) {
            return '已取消';
          } else if (status === 3) {
            return '已评分';
          } else if (status === 4) {
            return '审批';
          } else if (status === 5) {
            return '投诉中';
          }
        },
        width: '10%',
      },
      {
        title: '操作',
        dataIndex: 'id',
        render: (id, data) => {
          //如果预定时间超过了当前时间，返回退订按钮，否则返回不可退订
          if (new Date(data.datePeriod) > new Date()) {
            if (data.status === 4) {
              return (
                <>
                  <Button
                    onClick={() => {
                      refund(data.id);
                    }}
                  >
                    审批
                  </Button>
                </>
              );
            } else if (data.status === 1) {
              return (
                <>
                  <Button
                    onClick={() => {
                      refund(data.id);
                    }}
                  >
                    退款
                  </Button>
                </>
              );
            } else {
              return '不可退订';
            }
          } else if (data.status === 5) {
            return (
              <>
                <Button
                  onClick={() => {
                    getComplaints(data.id);
                  }}
                >
                  查看投诉
                </Button>
              </>
            );
          } else {
            return '不可退订';
          }
        },
        width: '10%',
      },
    ],
    [],
  );

  let complaintContent = '';
  const getComplaints = async (id: number) => {
    const complaint = await GetComplaintAPI(id);
    Modal.confirm({
      title: '投诉',
      content: (
        <div>
          <List
            itemLayout="horizontal"
            dataSource={complaint}
            renderItem={(item) => (
              <List.Item>
                <List.Item.Meta
                  title={item.senderType === 1 ? '用户' : '商家'}
                  description={item.commentContent}
                />
              </List.Item>
            )}
          />
          <Input
            style={{ marginTop: '10px' }}
            placeholder="请填写投诉内容"
            onChange={(e) => {
              complaintContent = e.target.value;
            }}
          />
        </div>
      ),
      async onOk() {
        const complaint: Complaint = {
          complaintId: id,
          senderId: localStorage.masterId,
          senderType: 0,
          commentContent: complaintContent,
        };
        await ComplaintAPI(complaint);
        console.log('OK');
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  //发送查询请求
  const fetchData = useCallback(async () => {
    setLoading(true);
    setData([]);
    try {
      const res = await getOrderAPI(queryPage);
      setData(res.records);
      setTableParams((prevParams) => ({
        ...prevParams,
        pagination: {
          current: res.current,
          pageSize: res.size,
          total: res.total,
          ...prevParams.pagination,
        },
      }));
    } finally {
      setLoading(false);
    }
  }, [tableParams]);

  //监听tableParams的变化
  useEffect(() => {
    fetchData();
  }, [JSON.stringify(tableParams)]);

  //监听queryPage的变化
  const handleTableChange = useCallback(
    (
      pagination: TablePaginationConfig = {},
      filters: Record<string, FilterValue> = {},
      sorter: SorterResult<DataType> = {},
    ) => {
      setTableParams({
        pagination,
        filters,
        ...sorter,
      });
      queryPage.current = (pagination && Number(pagination.current)) || 1;
      queryPage.size = (pagination && Number(pagination.pageSize)) || 10;
      //如果为undefined则转换为'' String类型
      queryPage.sortField = sorter && sorter.field ? String(sorter.field) : '';
      queryPage.sortOrder =
        sorter && sorter.order === 'descend'
          ? 'desc'
          : sorter && sorter.order === 'ascend'
          ? 'asc'
          : '';
    },
    [tableParams],
  );

  //搜索
  // const onSearch = useCallback(
  //   (value: string) => {
  //     queryPage.name = value;
  //     handleTableChange();
  //   },
  //   [handleTableChange],
  // );

  return (
    <div>
      <Form>
        <Search
          placeholder="菜品名称"
          allowClear
          enterButton="Search"
          size="small"
          // onSearch={onSearch}
          maxLength={10}
        />
      </Form>
      <Table
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        loading={loading}
        onChange={handleTableChange}
        pagination={tableParams.pagination}
        scroll={{ y: 530 }}
      />
    </div>
  );
};

export default App;
